<template>

        <div class="header-controls">
          <el-button  type="primary" @click="initDicom"> 初始化</el-button>

          <el-input v-model="studyInstanceUid" placeholder="请输入检查实例UID" style="width: 300px; margin-right: 10px;"
            disabled />
          <el-select v-model="seriesInstanceUid" placeholder="请选择序列实例" style="width: 300px; margin-right: 10px;">
            <el-option v-for="series in seriesInstanceUidOptions" :key="series.seriseId"
              :label="series.seriseId" :value="series.seriseId" />
          </el-select>

          <el-button type="primary" @click="loadDicomViewer" >
            加载影像
          </el-button>
        </div>

        <!-- DICOM图像显示区域 -->
        <div id="dicom-viewport" style="width: 512px; height: 512px; background-color: #000"></div>
      
    
</template>

<script>

import { getSeriseAllList } from "@/api/pacs/serise/serise"
import { DicomDataService } from '@/api/pacs/dicom/dicomService.js'
import {getSeriesImages} from '@/api/pacs/dicom/dicom.js'

import {
  createQiniuImageIds
} from "@/utils/dicom/dicom.js";


import {
  Enums as csEnums,
  RenderingEngine,
  imageLoader,
 
  init as coreInit
} from '@cornerstonejs/core'

import cornerstoneDICOMImageLoader from '@cornerstonejs/dicom-image-loader'
import { nextTick } from "vue";

export default {
    name: 'StudyDetailV1',
    data(){
        return{
            studyId:0,
            studyInstanceUid:'',
            seriesInstanceUidOptions:[],
            seriesInstanceUid:'',
            viewportRef:null,

            viewportId:'CT_STACK',
            renderingEngineId:'myRenderingEngine',
            viewPort:null,
            renderingEngine:null,
            
            // 创建DicomDataService实例
            dicomService:null,


        }
    },

    mounted(){
        this.dicomService = new DicomDataService();
        this.studyId = this.$route.query.studyId;
        if (this.studyId) {
            this.fetchSeriesList(this.studyId);
        } else {
        this.error = '未找到检查ID'
        }
    },

    methods: {
        async fetchSeriesList(studyIdValue) {
            this.seriesInstanceUidOptions = [] //为了方便遍历
            this.seriesInstanceUid = ''
            // try {
                // 调用后端API获取序列列表
                const response = await getSeriseAllList({studyId: this.studyId})
                this.seriesInstanceUidOptions = response.data || []

            // } catch (e) {
            //     console.log("====error===")
        
            // }    
        },

        async initDicom(){
            this.viewportRef=document.getElementById("dicom-viewport");
            console.log("====初始化开始====");
            await coreInit();
            await cornerstoneDICOMImageLoader.init();

            const tempRenderingEngine = new RenderingEngine(this.renderingEngineId);

            const viewportInput = {
                viewportId:this.viewportId,
                element:this.viewportRef,
                type: csEnums.ViewportType.STACK,
            };

    
            tempRenderingEngine.enableElement(viewportInput);

            this.renderingEngine=tempRenderingEngine;
            console.log("====初始化完成====")
        },

                
        /***
         * 显示Dicom图像
         */
        async loadDicomViewer(){


            const series = await getSeriesImages(this.studyId, this.seriesInstanceUid);
        
            const tempImageIds = series.data.images;

            if(this.renderingEngine==null){
                console.log("renderingEngine 为Null");
                return;
            }
            const tempViewPort = this.renderingEngine.getViewport(this.viewportId);
            //把imageIds 进行协议封装
            const imageIds=createQiniuImageIds(tempImageIds);
            console.log("imageIDs",imageIds);
            console.log("=====开始加载====")
            //注册七牛云加载器
            this.registerQiniuImageLoader();

            console.log("输出引擎",this.renderingEngine);
            console.log("输ViewPort",tempViewPort);
            console.log(typeof tempViewPort.setStack());
            if(!tempViewPort||typeof tempViewPort.setStack()!=='function'){
                console.log("tempViewPort 错误")
            }

            
            await tempViewPort.setStack(imageIds);
            console.log("输出-----",imageIds);
            // tempViewPort.render();
            console.log("加载完成")
        

        },
        /**
         * 注册七牛云图像加载器
         */
        registerQiniuImageLoader(){
            imageLoader.registerImageLoader('qiniu', (imageId) => {
                const loadPromise = new Promise(async (resolve, reject) => {
                try {
                    const url = imageId.replace('qiniu:', '');
                    

                    console.log('开始加载七牛云图像:', url);
                    const arrayBuffer = await this.dicomService.fetchDicomDataFromQiniu(url);

            
                    // 使用wadouri加载器
                    const blob = new Blob([arrayBuffer], { type: 'application/dicom' });
                    const blobUrl = URL.createObjectURL(blob);
                    const wadUriImageId = `wadouri:${blobUrl}`;
                    
                    console.log('使用wadouri加载器，临时imageId:', wadUriImageId);
                    
                    try {
                    const dicomImageLoader = cornerstoneDICOMImageLoader.wadouri.loadImage;
                
                    const imageLoadObject=dicomImageLoader(wadUriImageId);

                    console.log("imageLoadObject",imageLoadObject);
                    
                    const image = await imageLoadObject.promise;

                    console.log('通过wadouri加载器加载成功',image);
                    
                    
                    // URL.revokeObjectURL(blobUrl);
                
                    return image;

                    } catch (wadoError) {
                
                    console.error('wadouri加载器失败:', wadoError);
                    URL.revokeObjectURL(blobUrl);
                    reject(wadoError);
                    }

                } catch (error) {
                    console.error('七牛云图像加载失败:', error);
                    reject(error);
                }
                });

                return {
                    promise: loadPromise,
                    cancelFn: () => {
                        console.log('取消图像加载');
                    }
                };
            });
        },
    }
}




</script>
<style scoped>

</style>